<template>
  <div id="gsglBox">
    <el-row style="margin-bottom: 10px">
      <el-row>
        <template v-if="modelType">
          <el-button size="small" type="success" @click="handleCustomFormula"
            >自定义公式</el-button
          >
        </template>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete()"
          :disabled="!multipleForms.length"
          >全部删除</el-button
        >
      </el-row>
    </el-row>
    <!-- 遍历出来的表格 -->
    <el-scrollbar :height="height" ref="scrollbarRef" v-loading="loading">
      <div v-for="(item, index) in multipleForms" class="mutipleFormsClass">
        <el-form :model="item" label-width="80">
          <el-form-item label="公式表示：" prop="tableType">
            <div :class="'formulation' + index + 1"></div>
          </el-form-item>
          <el-form-item label="结果公式：" prop="isResult" v-show="modelType == 3">
            {{ item.isResult ? "否" : "是" }}
          </el-form-item>
          <el-form-item label="公式条件：" prop="formulaConditionDisplay" v-show="item.formulaConditionDisplay">
            {{ item.formulaConditionDisplay }}
          </el-form-item>
          <el-form-item label="备注：" prop="remark" v-show="item.remark">
            {{ item.remark }}
          </el-form-item>
          <el-table
            :data="item.formulaJclbList"
            style="margin-bottom: 10px"
            v-if="item.formulaJclbList?.length > 0"
          >
            <el-table-column
              align="center"
              prop="methodName"
              label="检测方法"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              prop="jclbName"
              label="检测类别"
              width="180"
              v-if="modelType == 3"
              show-overflow-tooltip
            />
          </el-table>
        </el-form>
        <el-row justify="end" style="margin-bottom: 10px">
          <el-button type="success" @click="copyFormula(item.formulaId)">复制</el-button>
          <el-button type="success" @click="editFormula(item.formulaId)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(item.formulaId)">删除</el-button>
        </el-row>
      </div>
      <div style="height: 20px"></div>
    </el-scrollbar>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="xygzOpen"
      title="修约规则配置"
      @close="xygzDialogClose"
      width="1200"
    >
      <el-row style="margin-bottom: 5px; margin-top: 5px">
        <p class="pinformation">修约规则</p>
        <p class="totalStyle">{{ xygzList.length }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button link type="success" icon="Plus" @click="ruleAdd1">新增</el-button>
        </el-row>
      </el-row>
      <el-table :data="xygzList" class="business" border style="margin-bottom: 10px">
        <el-table-column label="条件" align="center">
          <template #default="scope">
            <el-select
              placeholder="请选择条件"
              v-model="scope.row.conditionId"
              @change="changCondition1(scope.row)"
              clearable
            >
              <el-option
                v-for="dict in contitionList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="条件值" align="center" prop="conditionValue" width="140">
          <template #default="scope">
            <el-input
              clearable
              v-model="scope.row.conditionValue"
              placeholder="请输入条件值"
            />
          </template>
        </el-table-column>
        <el-table-column label="规则" align="center" prop="ruleTypeId">
          <template #default="scope">
            <el-select
              placeholder="请选择规则"
              filterable
              clearable
              v-model="scope.row.ruleTypeId"
            >
              <el-option
                v-for="dict in sys_rule2"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="规则约束" align="center" prop="ruleConditionId">
          <template #default="scope">
            <el-select
              placeholder="请选择规则约束"
              filterable
              clearable
              v-model="scope.row.ruleConditionId"
              @change="ruleConditionChange(scope.row)"
            >
              <el-option
                v-for="dict in sys_rule_condition"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="规则值" align="center" prop="ruleValue" width="140">
          <template #default="scope">
            <el-input
              clearable
              v-model="scope.row.ruleValue"
              placeholder="请输入规则值"
              :disabled="
                scope.row.ruleConditionId == 6 ||
                scope.row.ruleConditionId == 7 ||
                scope.row.ruleConditionId == 8
              "
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <el-button
              link
              type="success"
              icon="Delete"
              @click="handleListDelete1(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-table
        class="business"
        :data="handleJcxmList"
        v-loading="handleJcxmLoading"
        ref="handleJcxmTableRef"
        height="30vh"
        border
      >
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column label="前处理" align="center" width="130" prop="handleMc" />
        <el-table-column label="检测类别" align="center" :show-overflow-tooltip="true">
          <template #default="scope">{{ scope.row.jclbNames }}</template>
        </el-table-column>
        <el-table-column width="150" label="检测项目" align="center" prop="jcxmName">
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column
          label="机构检出限"
          align="center"
          prop="orgCheckLimit"
          width="150"
        />
        <el-table-column
          width="130"
          label="单位"
          align="center"
          prop="orgCheckLimitUnit"
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="xygzSave">确定</el-button>
          <el-button type="danger" @click="xygzOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      fullscreen
      :close-on-click-modal="false"
      v-model="customOpen"
      title="自定义公式"
      @close="dialogClose"
      width="1200"
    >
      <el-form
        :model="diyFormulaForm"
        ref="diyFormulaFormRef"
        label-width="80"
        :rules="diyFormulaRules"
      >
        <el-row>
          <p class="pinformation">字段清单</p>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button
              link
              style="margin-left: 15px"
              icon="plus"
              @click="handleOtherControls"
              >选择其它控件</el-button
            >
          </el-row>
        </el-row>
        <el-button
          link
          v-for="item in componentList"
          :key="item.componentId"
          :componentId="item.componentId"
          :tableId="item.tableId"
          style="margin: 0 10px"
          @click="insert(item.componentName, item.componentId, item.tableId)"
          class="formula_but"
          :style="`color: ${
            item.isOther ? '#ab00ff' : 'var(--theme-deep-color)'
          } !important`"
          >{{ item.componentName }}</el-button
        >
        <p class="pinformation" style="margin-top: 15px">公式</p>
        <el-row>
          <el-col :span="5">
            <el-form-item prop="resultId" label-width="0">
              <el-select
                style="width: 100%"
                clearable
                filterable
                placeholder="请选择公式"
                v-model="diyFormulaForm.resultId"
              >
                <el-option
                  v-for="item in componentList"
                  :key="item.componentId"
                  :label="item.componentName"
                  :value="item.componentId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center; line-height: 2">=</el-col>
          <el-col :span="17">
            <div
              v-if="customOpen"
              style="
                width: 100%;
                height: 100%;
                border: 1px solid #dcdfe6;
                border-radius: 5px;
              "
              contentEditable="true"
              class="formula_assemble"
            ></div>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="2" v-for="item in mathArray">
            <el-button
              type="success"
              class="formula_but"
              @click="insert(item.value)"
              style="width: 100%; margin-top: 5px"
              >{{ item.label }}</el-button
            >
          </el-col>
        </el-row>
        <p class="pinformation" style="margin-top: 15px" v-show="modelType == 3">规约</p>
        <el-row v-show="modelType == 3">
          <el-col :span="12">
            <el-form-item label="是否为最终结果公式：" prop="isResult" label-width="150">
              <el-select
                style="width: 100%"
                clearable
                filterable
                v-model="diyFormulaForm.isResult"
              >
                <el-option label="是" :value="0" />
                <el-option label="否" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="diyFormulaForm.isResult === 0 && modelType == 3">
          <p class="pinformation">适用检测类别</p>
          <p class="totalStyle">共 {{ diyMethodAndJclbList.length }} 条数据</p>
        </el-row>

        <el-table
          :data="diyMethodAndJclbList"
          @selection-change="diySelectionChange"
          ref="diyMethodAndJclbRef"
          v-if="diyFormulaForm.isResult === 0  && modelType == 3"
          max-height="20vh"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            align="center"
            prop="methodName"
            label="检测方法1"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.methodCode }}　{{ scope.row.methodName }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="jclbId" label="检测类别" width="500">
            <template #default="scope">
              <el-select
                v-model="scope.row.jclbId"
                placeholder="请选择"
                multiple
                collapse-tags
                collapse-tags-tooltip
                filterable
                style="width: 100%"
                :max-collapse-tags="4"
              >
                <el-option
                  v-for="item in scope.row.jclbList"
                  :key="item.jclbId"
                  :label="item.jclbName"
                  :value="item.jclbId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="修约规则" width="130">
            <template #default="scope">
              <el-button
                link
                @click="handleXygzConfig(scope.row, scope.$index)"
                icon="Setting"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row
          style="margin-bottom: 5px; margin-top: 5px"
          v-if="diyFormulaForm.isResult === 1 || modelType == 23"
        >
          <p class="pinformation">修约规则</p>
          <p class="totalStyle">共 {{ diyFormulaForm.ruleList?.length }} 条数据</p>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button link type="success" icon="Plus" @click="customRuleAdd"
              >新增</el-button
            >
          </el-row>
        </el-row>
        <el-table
          :data="diyFormulaForm.ruleList"
          v-if="diyFormulaForm.isResult === 1 || modelType == 23"
          class="business"
          border
          ref="jgRuleTableRef"
          style="margin-bottom: 10px"
        >
          <el-table-column label="条件" align="center">
            <template #default="scope">
              <el-select
                placeholder="请选择条件"
                v-model="scope.row.conditionId"
                @change="changCondition(scope.row)"
                clearable
              >
                <el-option
                  v-for="dict in contitionList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="条件值" align="center" prop="conditionValue">
            <template #default="scope">
              <el-input
                clearable
                v-model="scope.row.conditionValue"
                placeholder="请输入条件值"
              />
            </template>
          </el-table-column>
          <el-table-column label="规则" align="center" prop="ruleTypeId">
            <template #default="scope">
              <el-select
                placeholder="请选择规则"
                filterable
                clearable
                v-model="scope.row.ruleTypeId"
              >
                <el-option
                  v-for="dict in sys_rule2"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="规则约束" align="center" prop="ruleConditionId">
            <template #default="scope">
              <el-select
                placeholder="请选择规则约束"
                filterable
                clearable
                v-model="scope.row.ruleConditionId"
                @change="ruleConditionChange(scope.row)"
              >
                <el-option
                  v-for="dict in sys_rule_condition"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="规则值" align="center" prop="ruleValue">
            <template #default="scope">
              <el-input
                clearable
                v-model="scope.row.ruleValue"
                placeholder="请输入规则值"
                :disabled="
                  scope.row.ruleConditionId == 6 ||
                  scope.row.ruleConditionId == 7 ||
                  scope.row.ruleConditionId == 8
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="修约方式" align="center" prop="xyId">
            <template #default="scope">
              <el-select
                style="width: 100%"
                clearable
                filterable
                v-model="scope.row.xyId"
              >
                <el-option :value="0" label="四舍五入"></el-option>
                <el-option :value="1" label="四舍六入五成双"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button
                link
                type="success"
                icon="Delete"
                @click="handleCustomListDelete(scope.$index, 'ruleList')"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="公式条件：" style="margin-top: 5px;">
          <el-row style="width: 100%" :gutter="10">
            <el-col :span="8">
              <el-select style="width: 100%" clearable filterable placeholder="请选择公式" v-model="diyFormulaForm.temp1">
                <el-option v-for="(item, index) in componentList" :key="item.componentId" :label="item.componentName"
                  :value="index" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select style="width: 100%" placeholder="请选择条件" v-model="diyFormulaForm.temp2" clearable>
                <el-option v-for="(dict, index) in contitionList" :key="dict.value" :label="dict.label"
                  :value="dict.label"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input v-model="diyFormulaForm.temp3" clearable maxlength="100">
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="中间公式：" v-if="diyFormulaForm.isResult === 0 && modelType == 3">
          <el-select
            v-model="diyFormulaForm.relFormulaIds"
            placeholder="请选择"
            filterable
            multiple
            collapse-tags
            collapse-tags-tooltip
            style="width: 100%"
            :max-collapse-tags="2"
          >
            <el-option
              v-for="item in centerGsList"
              :key="item.formulaId"
              :label="item.formulaExpressDisplay"
              :value="item.formulaId"
            />
          </el-select>
        </el-form-item>
        <el-dialog
          :class="'el-dialog-theme3'"
          append-to-body
          draggable
          :close-on-click-modal="false"
          v-model="otherOpen"
          @close="otherDialogClose"
          title="选择其它控件"
        >
          <el-form-item label="其它模板：">
            <el-select
              v-model="otherConForm.tableId"
              placeholder="请选择"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              :remote-method="remoteMethod1"
              :loading="loading6"
              class="custom-select1"
              style="width: 100%"
              @change="otherTableChange"
            >
              <el-option
                v-for="item in mainList1"
                :key="item.tableId"
                :label="item.tableName"
                :value="item.tableId"
              >
                <el-tooltip class="box-item" effect="customized" placement="right">
                  <template #content>
                    {{ item.tableName }}
                  </template>
                  <div
                    style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis"
                  >
                    {{ item.tableName }}
                  </div>
                </el-tooltip>
              </el-option>
            </el-select>
          </el-form-item>
          <el-table
            :data="otherConList"
            class="business"
            @selection-change="handleSelectionChange"
            height="70vh"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="控件名称"
              align="center"
              prop="componentName"
            ></el-table-column>
          </el-table>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="success" @click="otherDefine">确定</el-button>
              <el-button type="danger" @click="otherOpen = false">关闭</el-button>
            </div>
          </template>
        </el-dialog>
        <el-row v-show="modelType == 23">
          <p class="pinformation" style="margin-top: 8px">关联方法</p>
          <p class="totalStyle" style="margin-top: 6px">
            共 {{ methodList.length }} 条数据
          </p>
          <el-row style="margin-left: 10px">
            <el-button link type="success" icon="plus" @click="handleAddMethod"
              >新增</el-button
            >
          </el-row>
        </el-row>

        <el-table :data="methodList" max-height="550px" v-show="modelType == 23">
          <el-table-column label="方法编号" align="center" prop="methodCode" />
          <el-table-column label="方法名称" align="center" prop="methodName" />
          <el-table-column label="操作" align="center" width="150">
            <template #default="scope">
              <el-button
                link
                icon="Edit"
                @click="handleMethodEdit(scope.row, scope.$index)"
                >编辑</el-button
              >
              <el-button link icon="Delete" @click="handleMethodDel(scope.row.methodId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <p class="pinformation" style="margin-top: 15px">备注</p>
        <el-input
          v-model="diyFormulaForm.remark"
          type="textarea"
          :rows="2"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="define">确定</el-button>
          <el-button type="danger" @click="customOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="methodOpen"
      :title="methodTitle"
      width="500"
    >
      <el-form-item label="检测方法：">
        <el-select
          v-model="methodId"
          filterable
          remote
          reserve-keyword
          remote-show-suffix
          :remote-method="remoteMethod"
          :loading="methodLoading"
          style="width: 100%"
        >
          <el-option
            v-for="item in methodOptionList"
            :key="item.methodId"
            :value="item.methodId"
            :label="item.methodCode + item.methodName"
          >
            <span v-html="getSupAndSub(item.methodName)"></span>
          </el-option>
        </el-select>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleMethodSave">确定</el-button>
          <el-button type="danger" @click="methodOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import bus from "@/utils/eventBus";
import {
  listMethod,
  diyFormulaSave,
  getGsList,
  getEditForm,
  delGsList,
  delAllGsList,
  listTableMain,
  getTableTem,
  getFormulaMethodList,
  getInterFormulaList,
  queryHandleJcxmList,
  getModelType,
  getSuitList1,
} from "@/api/templateEditor/table";
import { parseStrEmpty } from "@/utils/ruoyi";
const modelType = ref();
const route = useRoute();
const { proxy } = getCurrentInstance();
const contitionList = ref([
  { value: ">", label: ">" },
  { value: "<", label: "<" },
  { value: ">=", label: "≥" },
  { value: "<=", label: "≤" },
  { value: "==", label: "=" },
]);
const { sys_rule1, sys_rule_condition, sys_rule2 } = proxy.useShareDict(
  "sys_rule1",
  "sys_rule_condition",
  "sys_rule2"
);

const loading = ref(false);
const handleJcxmLoading = ref(false);
const multipleForms = ref([]);
const methodList = ref([]);
const methodOpen = ref(false);
const methodTitle = ref();
const methodId = ref();
const editMethodIndex = ref();
const methodLoading = ref(false);
const methodOptionList = ref([]);

// 数学方法
const mathArray = ref([
  { label: "加", value: "+" },
  { label: "减", value: "-" },
  { label: "乘", value: "*" },
  { label: "除", value: "/" },
  { label: "最后数字", value: "last()" },
  { label: "左括号", value: "(" },
  { label: "右括号", value: ")" },
  { label: "绝对值", value: "abs()" },
  { label: "平方根", value: "sqrt()" },
  { label: "随机数", value: "random()" },
  { label: "正弦值", value: "sin()" },
  { label: "余弦值", value: "cos()" },
  { label: "正切值", value: "tan()" },
  { label: "反正弦值", value: "asin()" },
  { label: "反余弦值", value: "acos()" },
  { label: "反正切值", value: "atan()" },
  { label: "角度", value: "atan2()" },
  { label: "自然对数", value: "log10()" },
  { label: "x次幂", value: "exp(x)" },
  { label: "x的y次幂", value: "pow(x,y)" },
  { label: "最大值", value: "max()" },
  { label: "最小值", value: "min()" },
  { label: "四舍五入", value: "round()" },
  { label: "最小整数", value: "ceil()" },
  { label: "最大整数", value: "floor()" },
]);

const rules = ref({
  methodId: [{ required: true, message: "适用方法不能为空", trigger: "blur" }],
  formulaId: [{ required: true, message: "公式不能为空", trigger: "blur" }],
  isResult: [{ required: true, message: "是否为最终结果公式不能为空", trigger: "blur" }],
  followParam: [{ required: true, message: "修约跟随参数不能为空", trigger: "blur" }],
  ruleId: [{ required: true, message: "修约规则不能为空", trigger: "blur" }],
  modeId: [{ required: true, message: "修约方法不能为空", trigger: "blur" }],
  digitCount: [{ required: true, message: "修约位数不能为空", trigger: "blur" }],
  jclbId: [{ required: true, message: "适用类别不能为空", trigger: "blur" }],
});

const diyFormulaRules = ref({
  resultId: [{ required: true, message: "公式不能为空", trigger: "blur" }],
  isResult: [{ required: true, message: "是否为最终结果公式不能为空", trigger: "blur" }],
  followParam: [{ required: true, message: "修约跟随参数不能为空", trigger: "blur" }],
  ruleId: [{ required: true, message: "修约规则不能为空", trigger: "blur" }],
  modeId: [{ required: true, message: "修约方法不能为空", trigger: "blur" }],
  digitCount: [{ required: true, message: "修约位数不能为空", trigger: "blur" }],
});
getModelType(route.query.tableId).then((res) => {
  modelType.value = res.data.modelType;
});
const handleJcxmList = ref([]);
function getList() {
  loading.value = true;
  getGsList({ tableId: route.query.tableId }).then((res) => {
    loading.value = false;
    if (!res.data.length) {
      multipleForms.value = [];
      return;
    }
    multipleForms.value = res.data;
    nextTick(() => {
      multipleForms.value.forEach((item1, index) => {
        const divElement = document.querySelector(".formulation" + index + 1);
        divElement.innerText = "";
        let expressList = item1.formulaExpressDisplay.split("φ");
        expressList.forEach((item) => {
          let isComponent = item.split("Ψ");
          if (isComponent.length > 1) {
            let spanElement = document.createElement("span");
            spanElement.setAttribute("componentId", isComponent[0]);
            spanElement.setAttribute("contenteditable", "false");
            spanElement.textContent = isComponent[1];
            spanElement.className = "to_show_span";
            spanElement.style.cursor = "pointer";
            spanElement.addEventListener("click", function () {
              bus.emit("selectFormula", isComponent[0]);
            });
            divElement.appendChild(spanElement);
          } else {
            let textNode = document.createTextNode(item);
            divElement.appendChild(textNode);
          }
        });
      });
    });
  });
}

getList();
// ----------------------------- 匹配方法公式操作 ------------------------------

const open = ref(false);
const jclbList = ref([]);
const xygzList = ref([]);
const formulaForm = ref({
  tableId: route.query.tableId,
  isResult: 0,
  followParam: 0,
  ruleList: [],
});
const gsList = ref([]);
const componentList = ref([]);

function getMethod() {
  listMethod(route.query.tableId).then((res) => {
    methodList.value = res.data;
  });
}

function dialogClose() {
  formulaForm.value = {
    tableId: route.query.tableId,
    isResult: 0,
    followParam: 0,
    ruleList: [],
  };
  diyFormulaForm.value = {
    tableId: route.query.tableId,
    isResult: 0,
    followParam: 0,
    ruleList: [],
    formulaJclbList: [],
    relFormulaIds: [],
  };
  proxy.$refs["formulaFormRef"]?.clearValidate();
  proxy.$refs["diyFormulaFormRef"]?.clearValidate();
  proxy.$refs["diyMethodAndJclbRef"]?.clearSelection();
  componentList.value = componentList.value.filter((item) => {
    return item.isOther !== 1;
  });
  methodList.value = [];
  jclbList.value = [];
  gsList.value = [];
  let divElement = document.querySelector(".formula_assemble");
  if (divElement) {
    divElement.innerText = "";
  }
}

// -------------------------------- 自定义公式操作 --------------------------------
const customOpen = ref(false);
const diyFormulaForm = ref({
  tableId: route.query.tableId,
  isResult: 0,
  followParam: 0,
  ruleList: [],
  formulaJclbList: [],
  relFormulaIds: [],
});

const centerGsList = ref([]);

const diyMethodAndJclbList = ref([]);

function handleCustomFormula() {
  customOpen.value = true;
  if (modelType.value == 3) {
    diyFormulaForm.value.isResult = 0;
    getMethodAndJclbList(false);
  } else {
    diyFormulaForm.value.isResult = 1;
  }
}

watch(
  () => diyFormulaForm.value.formulaJclbList,
  () => {}
);

function getMethodAndJclbList(isBs) {
  getFormulaMethodList({
    tableId: route.query.tableId,
    formulaId: diyFormulaForm.value.formulaId,
  }).then((res) => {
    diyMethodAndJclbList.value = res.data;
    if (isBs) {
      nextTick(() => {
        if (
          diyFormulaForm.value.formulaJclbList &&
          diyFormulaForm.value.formulaJclbList.length > 0
        ) {
          diyFormulaForm.value.formulaJclbList.forEach((item) => {
            diyMethodAndJclbList.value.forEach((item1) => {
              if (item.tMId == item1.tMId) {
                item1.jclbId = item.jclbId;
                proxy.$refs["diyMethodAndJclbRef"].toggleRowSelection(item1);
              }
            });
          });
        }
      });
    }
  });
  getInterFormulaList({ tableId: route.query.tableId }).then((res) => {
    centerGsList.value = res.data;
  });
}

function diySelectionChange(selectList) {
  diyFormulaForm.value.formulaJclbList = selectList;
}

function define() {
  proxy.$refs["diyFormulaFormRef"].validate((valid) => {
    if (valid) {
      debugger;
      const divElement = document.querySelector(".formula_assemble");
      if (!divElement.hasChildNodes()) {
        proxy.$modal.msgError("请输入完整公式！");
        return;
      }
      if (!diyFormulaForm.value.isResult) {
        //0:最终结果公式
        let isNext = true;
        if (
          diyFormulaForm.value.formulaJclbList &&
          diyFormulaForm.value.formulaJclbList.length > 0
        ) {
          for (const item of diyFormulaForm.value.formulaJclbList) {
            if (!item.jclbId) {
              isNext = false;
              break;
            }
          }
        }
        if (!isNext) {
          proxy.$modal.msgError("请将选取的适用检测类别补充完整！");
          return;
        }
      } else {
      }
      diyFormulaForm.value.formulaExpressDisplay =
        proxy.getItemByArray(
          componentList.value,
          "componentId",
          diyFormulaForm.value.resultId,
          "componentName"
        ) + "=";
      divElement.childNodes.forEach((node) => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          diyFormulaForm.value.formulaExpressDisplay += node.textContent;
        } else if (node.nodeType === Node.TEXT_NODE) {
          diyFormulaForm.value.formulaExpressDisplay += node.nodeValue;
        }
      });

      const spanElements = divElement.querySelectorAll("span[componentId]");
      diyFormulaForm.value.componentList = [];
      Array.from(spanElements).map((spanElement) => {
        diyFormulaForm.value.componentList.push({
          componentId: spanElement.getAttribute("componentId"),
          tableId: spanElement.getAttribute("tableId"),
        });
      });

      const childNodes = divElement.childNodes;
      diyFormulaForm.value.formulaExpress = diyFormulaForm.value.resultId + "=";
      Array.from(childNodes).forEach((node) => {
        if (node instanceof HTMLSpanElement) {
          const componentId = node.getAttribute("componentId");
          if (componentId) {
            diyFormulaForm.value.formulaExpress += componentId;
          } else {
            diyFormulaForm.value.formulaExpress += node.innerText;
          }
        } else {
          diyFormulaForm.value.formulaExpress += node.textContent;
        }
      });
      if (modelType.value == 23) {
        diyFormulaForm.value.methodIds = methodList.value.map((item) => {
          return item.methodId;
        });
      }
      if (
        diyFormulaForm.value.temp1 === 0 ||
        diyFormulaForm.value.temp1 ||
        diyFormulaForm.value.temp2 ||
        diyFormulaForm.value.temp3
      ) {
        if (
          (diyFormulaForm.value.temp1 === 0 || diyFormulaForm.value.temp1) &&
          diyFormulaForm.value.temp2 &&
          diyFormulaForm.value.temp3
        ) {
          diyFormulaForm.value.formulaCondition =
            "φ" +
            componentList.value[diyFormulaForm.value.temp1].componentId +
            "φ" +
            diyFormulaForm.value.temp2 +
            "'" + diyFormulaForm.value.temp3 + "'";
          diyFormulaForm.value.formulaConditionDisplay =
            componentList.value[diyFormulaForm.value.temp1].componentName +
            diyFormulaForm.value.temp2 +
            diyFormulaForm.value.temp3;
        } else {
          delete diyFormulaForm.value.formulaCondition;
          delete diyFormulaForm.value.formulaConditionDisplay;
          proxy.$modal.msgError("公式条件不完整！");
          return;
        }
      } else {
        delete diyFormulaForm.value.formulaCondition;
        delete diyFormulaForm.value.formulaConditionDisplay;
      }
      diyFormulaSave(diyFormulaForm.value).then((res) => {
        customOpen.value = false;
        getList();
        proxy.$modal.msgSuccess("保存成功");
      });
    }
  });
}

function getRange() {
  const selection = window.getSelection();
  if (selection.getRangeAt && selection.rangeCount > 0) {
    return { range: selection.getRangeAt(0), selection };
  }

  const formulaAssemble = document.querySelector(".formula_assemble");
  const range = document.createRange();
  range.selectNodeContents(formulaAssemble);
  range.collapse(false);
  return { range: range, selection };
}

function getSpan(className, text, id, tableId) {
  if (id) {
    const span = document.createElement("span");
    span.className = className;
    span.innerText = text;
    span.setAttribute("contenteditable", "false");
    span.setAttribute("componentId", id);
    span.setAttribute("tableId", tableId);
    return span;
  } else {
    return document.createTextNode(text);
  }
}

function insert(num, id, tableId) {
  const { range } = getRange();
  const span = getSpan("to_show_span", num, id, tableId);

  const formulaAssemble = document.querySelector(".formula_assemble");
  if (
    range.commonAncestorContainer === formulaAssemble ||
    (range.commonAncestorContainer.nodeType === Node.TEXT_NODE &&
      range.commonAncestorContainer.parentNode === formulaAssemble)
  ) {
    range.insertNode(span);
  } else {
    let lastChild = formulaAssemble.lastElementChild;
    if (!lastChild) {
      lastChild = formulaAssemble.lastChild;
    }
    if (lastChild && lastChild.nodeType === Node.TEXT_NODE) {
      formulaAssemble.insertBefore(span, lastChild.nextSibling);
    } else {
      formulaAssemble.appendChild(span);
    }
  }

  const newRange = document.createRange();
  newRange.setStartAfter(span);
  newRange.setEndAfter(span);

  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(newRange);

  formulaAssemble.focus();
}

const height = ref();

// ----------------编辑--------------

function editFormula(val) {
  return new Promise((resolve, reject) => {
    getEditForm(val).then((res) => {
      if(res.data.methodList){
        methodList.value = res.data.methodList;
        delete res.data.methodList;
      }
      diyFormulaForm.value = res.data;
      if (res.data.formulaCondition) {
        for (let i = 0; i < componentList.value.length; i++) {
          if (
            componentList.value[i].componentId ===
            res.data.formulaCondition.split("φ")[1]
          ) {
            diyFormulaForm.value.temp1 = i;
            break;
          }
        }
        let temp = res.data.formulaCondition.split("φ")[2];
        diyFormulaForm.value.temp2 = temp.charAt(0); // 获取第一个字符
        const condtionValue = temp.slice(1);
        if(condtionValue.indexOf("'") == 0){
        diyFormulaForm.value.temp3 = condtionValue.replaceAll("'",""); // 从索引为1的位置开始截取到末尾
        }else{
        diyFormulaForm.value.temp3 = condtionValue; // 从索引为1的位置开始截取到末尾
      }
      }
      if (modelType.value == 3) {
        getMethodAndJclbList(true);
      }
      customOpen.value = true;
      // getMethod();
      // if (diyFormulaForm.value.methodId) {
      //   listJclb(diyFormulaForm.value.methodId).then((res) => {
      //     jclbList.value = res.data;
      //   });
      // }
      resolve();
      nextTick(() => {
        const divElement = document.querySelector(".formula_assemble");
        if (diyFormulaForm.value.formulaExpress.charAt(0) === "φ") {
          diyFormulaForm.value.formulaExpress = diyFormulaForm.value.formulaExpress.slice(
            1
          );
        }
        let expressList = diyFormulaForm.value.formulaExpress.split("φ");
        expressList.forEach((item) => {
          let isComponent = item.split("Ψ");
          if (isComponent.length > 1) {
            let spanElement = document.createElement("span");
            spanElement.setAttribute("componentId", isComponent[0]);
            spanElement.setAttribute("tableId", isComponent[2]);
            spanElement.setAttribute("contenteditable", "false");
            spanElement.textContent = isComponent[1];
            spanElement.className = "to_show_span";
            divElement.appendChild(spanElement);
          } else {
            let textNode = document.createTextNode(item);
            divElement.appendChild(textNode);
          }
        });
      });
    });
  });
}

function copyFormula(val) {
  editFormula(val).then((res) => {
    delete diyFormulaForm.value.formulaId;
  });
}

// -------------删除---------------
function handleDelete(id) {
  const confirmMessage = id ? "确定要删除吗？" : "确定要全部删除吗？";
  proxy.$modal
    .confirm(confirmMessage)
    .then(async () => {
      loading.value = true;
      if (id) {
        await delGsList(id);
      } else {
        await delAllGsList(route.query.tableId);
      }
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    })
    .catch(() => {
      loading.value = false;
    });
}

// ---------------------------修约规则----------------------------

function ruleAdd() {
  formulaForm.value.ruleList.push({ disabled: true });
}

function customRuleAdd() {
  diyFormulaForm.value.ruleList.push({ disabled: true });
}

function changCondition(row) {
  delete row.conditionValue;
}

function handleCustomListDelete(index, listName) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      let list = eval("diyFormulaForm.value." + listName);
      list.splice(index, 1);
    })
    .catch(() => {});
}

function ruleAdd1() {
  xygzList.value.push({ disabled: true });
}

function changCondition1(row) {
  delete row.conditionValue;
}

function handleListDelete1(index) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      let list = xygzList.value;
      list.splice(index, 1);
    })
    .catch(() => {});
}

//验证规则列表是否填写完整
function validateRuleList1() {
  let ruleList = xygzList.value;
  let flag = true;
  for (let rule of ruleList) {
    if (
      !rule.ruleTypeId ||
      (rule.conditionId &&
        rule.ruleConditionId != 6 &&
        parseStrEmpty(rule.conditionValue).length == 0) ||
      (rule.ruleTypeId != 3 &&
        rule.ruleConditionId != 6 &&
        parseStrEmpty(rule.ruleValue).length == 0)
    ) {
      flag = false;
      break;
    }
  }
  return flag;
}

bus.on("tempComponent", (val) => {
  componentList.value = val.filter((item) => {
    return item.isHide == 0;
  });
});

const loading6 = ref(false);
const loading7 = ref(false);
const mainList = ref([]);
const mainList1 = ref([]);
function remoteMethod2(val) {
  if (val) {
    loading6.value = true;
    setTimeout(() => {
      let temp = {
        tableMain: 0,
        tableName: val,
        params: {},
      };
      temp.params["filterTableId"] = route.query.tableId;
      listTableMain(temp).then((res) => {
        loading6.value = false;
        mainList.value = res.rows;
      });
    }, 200);
  } else {
    mainList.value = [];
  }
}

function remoteMethod1(val) {
  if (val) {
    loading7.value = true;
    setTimeout(() => {
      let temp = {
        tableMain: 0,
        tableName: val,
        params: {},
      };
      temp.params["filterTableId"] = route.query.tableId;
      listTableMain(temp).then((res) => {
        loading7.value = false;
        mainList1.value = res.rows;
      });
    }, 200);
  } else {
    mainList1.value = [];
  }
}

// --------------------------------------选择其它控件--------------------------------------
const otherOpen = ref(false);
const otherConForm = ref({});
const otherConList = ref([]);
const beforDefine = ref([]);
function handleOtherControls() {
  otherOpen.value = true;
}

function otherTableChange(val) {
  getTableTem(val).then((res) => {
    otherConList.value = res.data;
  });
}

function handleSelectionChange(selection) {
  beforDefine.value = selection;
}

function otherDefine() {
  if (beforDefine.value.length === 0) {
    proxy.$modal.confirm("未选取其它控件，确定要关闭吗？").then(() => {
      otherOpen.value = false;
    });
  } else {
    beforDefine.value.forEach((item) => {
      item.tableId = otherConForm.value.tableId;
      item.isOther = 1;
    });
    componentList.value = componentList.value.concat(beforDefine.value);
    componentList.value = Array.from(
      new Set(componentList.value.map((item) => item.componentId))
    ).map((componentId) => {
      return componentList.value.find((item) => item.componentId === componentId);
    });
    otherOpen.value = false;
  }
}

function otherDialogClose() {
  otherConForm.value.tableId = "";
  otherConList.value = [];
}

function getHeight() {
  height.value = proxy.getSubFileHeight(proxy, "scrollbarRef");
}

function getMountedHeight() {
  nextTick(() => {
    getHeight();
    window.addEventListener("resize", getHeight);
  });
}

function getUnmountHeight() {
  window.removeEventListener("resize", getHeight);
}

const xygzOpen = ref(false);
const xygzIndex = ref();
function handleXygzConfig(row, index) {
  xygzOpen.value = true;
  row.ruleList = row.ruleList || [];
  xygzList.value = JSON.parse(JSON.stringify(row.ruleList));
  xygzIndex.value = index;
  if (row.methodId) {
    handleJcxmLoading.value = true;
    queryHandleJcxmList({ methodId: row.methodId })
      .then((res) => {
        if (!res.data) {
          handleJcxmList.value = [];
        } else {
          handleJcxmList.value = res.data;
        }
        handleJcxmLoading.value = false;
      })
      .catch((e) => {
        handleJcxmList.value = [];
        handleJcxmLoading.value = false;
      });
  }
}

function xygzSave() {
  if (!validateRuleList1()) {
    proxy.$modal.msgError("请将修约规则补充完整！");
    return;
  }
  diyMethodAndJclbList.value[xygzIndex.value].ruleList = JSON.parse(
    JSON.stringify(xygzList.value)
  );
  xygzOpen.value = false;
}

function xygzDialogClose() {
  xygzList.value = [];
}

defineExpose({
  getMountedHeight,
  getUnmountHeight,
});

function handleAddMethod() {
  methodOpen.value = true;
  editMethodIndex.value = undefined;
  methodId.value = undefined;
}

function remoteMethod(methodCode) {
  if (methodCode) {
    if (methodCode.length <= 2) {
      return;
    }
    methodLoading.value = true;
    setTimeout(() => {
      let params = {
        methodCode: methodCode,
        tableId: route.query.tableId,
        params: { onlyMethod: true },
      };
      getSuitList1(params).then((res) => {
        methodLoading.value = false;
        methodOptionList.value = res.data;
      });
    }, 200);
  }
}

function ruleConditionChange(row) {
  if (row.ruleConditionId == 6 || row.ruleConditionId == 7 || row.ruleConditionId == 8) {
    row.ruleValue = "";
  }
  if (row.ruleConditionId == 8) {
    row.ruleTypeId = undefined;
  }
}

function handleMethodEdit(row, index) {
  debugger;
  handleAddMethod();
  methodOptionList.value = [
    { methodId: row.methodId, methodCode: row.methodCode, methodName: row.methodName },
  ];
  methodId.value = row.methodId;
  editMethodIndex.value = index;
}

function handleMethodDel(selectedMethodId) {
  for (let i in methodList.value) {
    if (methodList.value[i].methodId == selectedMethodId) {
      methodList.value.splice(i, 1);
      proxy.$modal.msgSuccess("删除成功！");
      break;
    }
  }
}

function handleMethodSave() {
  if (!methodId.value) {
    proxy.$modal.msgError("请输入检测方法！");
    return;
  }
  const selectedMethod = methodOptionList.value.find((method) => {
    return method.methodId == methodId.value;
  });
  if (!selectedMethod) {
    proxy.$modal.msgError("请输入检测方法！");
    return;
  }
  if (typeof editMethodIndex.value == "number") {
    if (
      methodList.value.some(
        (item, index) => editMethodIndex.value != index && item.methodId == methodId.value
      )
    ) {
      proxy.$modal.msgError("该检测方法已经存在！");
      return;
    }
    methodList.value.splice(editMethodIndex.value, 1);
    methodList.value.splice(editMethodIndex.value, 1, selectedMethod);
  } else {
    if (methodList.value.some((item) => item.methodId == methodId.value)) {
      proxy.$modal.msgError("该检测方法已经存在！");
      return;
    }
    methodList.value.push(selectedMethod);
  }
  methodOpen.value = false;
}
</script>

<style lang="scss" scoped>
.mutipleFormsClass {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid;
  border-radius: 15px;
}

:deep(.to_show_span) {
  background-color: skyBlue !important;
  color: #fff !important;
  margin: 0 5px;
  border-radius: 5px;
  padding: 3px 10px;
  height: 20px;
}
</style>
